import Vue from 'vue'
import Router from 'vue-router'
import store from "@/store";
import {Message} from "element-ui";

const contexts = require.context('../views',true,/^(?!.*\/component\/).*\.vue$/)
const routers = [];
contexts.keys().forEach(key=>{
    // 获取组件配置
    const componentConfig = contexts(key).default;
    // 剥去文件名开头的 `./` 和`.vue`结尾的扩展名 businessManagement/tokenManagement
    const routePath = key.replace(/^\.\//,'').replace(/\.vue$/,'');
    // /tokenManagement
    const path = ('/'+routePath).match(/\/\w*$/)
    // 全局注册组件
    routers.push({
        path: path[0],
        name: componentConfig.name,
        component: resolve => require([`../views/${routePath}`],resolve)
    })
})

Vue.use(Router)
let route = [
    {
        path: '/login',
        name: 'login',
        hidden: true,
        component: () => import(`@/views/login/index.vue`),
        meta: {
            hidden: true,
        }
    },
    //
    {
        path: '/',
        name: 'Layout',
        hidden: true,
        component: () => import(`@/layout/index.vue`),
        redirect: '/home',
        meta: {
            title: "系统管理"
        },
        children: [
            ...routers,
        ]
    },
    {
        path: "*",
        name: '404none',
        component: () => import('@/views/none/404.vue')
    }
]

let base = `${process.env.BASE_URL}` // 动态获取二级目录
const router = new Router({
    mode: 'hash', // 路由有两种模式：history、hash，想要不带#号就选history，默认是hash模式
    base: base,
    routes: route,
});

router.beforeEach((to, from, next) => {
    if(to.name === 'login'){
        next()
    }else {
        next()
        /*if( !sessionStorage.getItem('userInfo')){
            if (store.state.login.userInfo){
                Message.warning('请重新登陆!')
            }
            next('login')
        }else {
            next()
        }*/
    }
})
// 修复路由跳转问题
const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
// 修改原型对象中的push函数
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
// 修改原型对象中的replace函数
Router.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}

export {route}
export default router;
